#include "plugin_init.h"

using namespace std;
using namespace nmsp;
using namespace httplib;

// $ curl --insecure https://rtc.zhangxi123.com/111.txt
// $ curl --insecure https://rtc.zhangxi123.com/chat_webrtc/index.html -o 111.html
// # --insecure   证书过期,
// $ curl -H https://rtc.zhangxi123.com/111.txt  http://10.4.7.22:8585/qq
// $ curl -H https://rtc.zhangxi123.com/111.txt  http://10.4.7.22:8585/zhangxi123?vkey=123456&name=zhangxi
// # 这里不需要 --insecure https://rtc.zhangxi123.com/111.txt 因为已经走代理 http://10.4.7.22:8585/ 了

#define VKEY "vkey"
#define VKEY_VALUE "123456"
#define USERNAME "name"
#define USERNAME_VALUE "zhangxi"
#define CACHE_FILE "1x1x1x.txt"
#define SERVER_GATEWAY_TIMEOUT 504

// typedef std::function<void(Cont*, const httplib::Request &, httplib::Response &)> PluginCallback;
static void zhangxi_plugin(Contp contp, const httplib::Request &req, httplib::Response &resp)
{
    MYLOG("zhangxi123====================zhangxi123=====================\n");
    // 1. 检查 vkey,
    httplib::Params params = req.params;
    std::string vkey = "";
    std::string username = "";
    if (1 == params.count(VKEY))
    {
        vkey = params.find(VKEY)->second;
    }
    if (1 == params.count(USERNAME))
    {
        username = params.find(USERNAME)->second;
    }

    MYLOG("vkey = %s, name = %s", vkey.c_str(), username.c_str());
    // if (VKEY_VALUE != vkey || USERNAME_VALUE != username)
    if (VKEY_VALUE != vkey)
    {
        const char *fmt = "<span style='color:red;'>%s</span></p>\n";
        char buf[BUFSIZ];
        snprintf(buf, sizeof(buf), fmt, "Access zhangxi123 param error ...");
        resp.set_content(buf, "text/html");
        return;
    }

    // 2. 检查缓存过期, 假设缓存未过期, 这里也不进行缓存分片处理,
    // 假设 111.txt 缓存下来的文件是 1x1x1x.txt

    if (0 != access(CACHE_FILE, F_OK))
    {
        const char *fmt = "<p>Error Status: <span style='color:red;'>%d:%s</span></p>\n";
        char buf[BUFSIZ];
        snprintf(buf, sizeof(buf), fmt, SERVER_GATEWAY_TIMEOUT, "cdn back-to-source error");
        resp.set_content(buf, "text/html");
        return;
    }

    // 3. 响应客户端,
    FILE *pf = fopen(CACHE_FILE, "r");
    if (pf == nullptr)
    {
        // MYLOG() ...
        // resp.set_content();
    }
    char context[1024] = {0};
    fgets(context, 1024, pf);
    fclose(pf);

    resp.set_content(context, "text/plain");
    return;
}

extern "C"
{
    void PluginInit(int sessionId, void *session);
}

void PluginInit(int sessionId, void *session)
{
    MYLOG("=================== zhangxi123 ===================");
    Cont *contp = ContCreate(std::bind(zhangxi_plugin, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3), "/zhangxi123", nullptr);
    HttpHookAdd(HTTP_READ_REQUEST_HDR_HOOK, contp);
}
